const AppConfig = {
  count: 1,
  configApi: '' as URL | string,
  _cache: {
    data: {} as Obj,
    updateAt: 0,
    time: 5 * 60, // seconds
    // time: 5, // seconds
  },
  _promise: null as Promise<any> | null,

  _hasCache() {
    const hasData = Object.keys(AppConfig._cache.data).length > 0;
    // const isFresh =
    //   Date.now() - AppConfig._cache.updateAt < AppConfig._cache.time * 1000;
    // return hasData && isFresh;
    return hasData;
  },

  async _updateCache(data: Obj) {
    AppConfig._cache.data = data;

    const saveRes = await fetch(AppConfig.configApi, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    }).then(res => res.json());

    // AppConfig._cache.data = saveRes.data;
    AppConfig._cache.updateAt = Date.now();
    console.log('🚀 ~ _updateCache ~ AppConfig._cache:', AppConfig._cache);
  },

  fetch() {
    // if exists promise, return it
    if (AppConfig._promise) {
      return AppConfig._promise;
    }

    process.env.NEXT_PUBLIC_GAID;
    const CONFIG_CENTER_API = process.env.NEXT_PUBLIC_CONFIG_CENTER_API;
    const APPID = process.env.NEXT_PUBLIC_CONFIG_CENTER_APPID;
    const SECRET = process.env.NEXT_PUBLIC_CONFIG_CENTER_SECRET;
    const APP_ENV = process.env.NEXT_PUBLIC_APP_ENV;
    if (!CONFIG_CENTER_API) {
      return Promise.resolve({});
    }

    const api = `${CONFIG_CENTER_API}?appid=${APPID}&env=${APP_ENV}`;

    // console.log('🚀 ~ AppConfig ~ fetch ~ api:', api);
    const headers = new Headers();
    headers.append('X-App-Secret', SECRET ?? '');
    // headers.append('Content-Type', 'application/json');

    const promise = fetch(api, {
      method: 'GET',
      headers,
      cache: 'no-store',
    })
      .then(res => res.json())
      .then(res => {
        const data = res.data;
        console.log('🚀 ~ AppConfig ~ fetch ~ data:', data, api);
        AppConfig._updateCache(data);
        AppConfig._promise = null;
        return data;
      })
      .catch(err => {
        console.log('🚀 ~ AppConfig ~ axios.get ~ err:', err?.message);
        AppConfig._promise = null;
        return Promise.resolve({});
      });

    AppConfig._promise = promise;

    return promise;
  },

  async get(refUrl: string) {
    // console.log(
    //   '🚀 ~ inputing get ~ refUrl:',
    //   refUrl,
    //   process.env.NEXT_PUBLIC_MY_DOMAIN
    // );
    // domain of req.url is localhost:3000, should use the url displayed in browser
    refUrl = process.env.NEXT_PUBLIC_MY_DOMAIN || refUrl;
    AppConfig.configApi = new URL('/api/configFile', refUrl);
    // console.log('🚀 ~ get ~ AppConfig.configApi:', AppConfig.configApi);

    const res = await fetch(AppConfig.configApi).then(res => res.json());
    if (res.success) {
      AppConfig._cache.data = res.data;
      return res.data;
    }

    // no cache, send request
    return AppConfig.fetch();
  },

  refresh(refUrl: string) {
    refUrl = process.env.NEXT_PUBLIC_MY_DOMAIN || refUrl;
    console.log('🚀 ~ AppConfig  REFRESH CACHE!');
    AppConfig.configApi = new URL('/api/configFile', refUrl);
    return AppConfig.fetch();
  },
};

export { AppConfig };
